package br.com.nautical.interfaces.managerBean;

import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;

import br.com.nautical.interfaces.Bean;
import br.com.nautical.persistence.model.Cliente;
import br.com.nautical.persistence.model.servicos.ClienteServicos;

@ManagedBean
public class ClienteBean implements Bean {

	private Cliente cliente = new Cliente();
	
	private List<Cliente> clientes;
	
	@Override
	public void gravar() {
		EntityManager manager = this.getEntityManager();
		
		ClienteServicos cliente = new ClienteServicos(manager);
		cliente.gravar(this.cliente);
		
		//Instancia Nova Classe
		this.cliente = new Cliente();
		this.cliente = null;
	}

	@Override
	public void remover() {
		EntityManager manager = this.getEntityManager();
		ClienteServicos cliente = new ClienteServicos(manager);
		
		cliente.remover(this.cliente);
		
		//Instancia nova Classes
		this.cliente = new Cliente();
		this.cliente = null;
	}

	@Override
	public void alterar() {
		EntityManager manager = this.getEntityManager();
		ClienteServicos cliente = new ClienteServicos(manager);
		
		cliente.alterar(this.cliente);
		
		//Instancia nova Classes
		this.cliente = new Cliente();
		this.cliente = null;
	}

	public List<Cliente> buscaTodosClientes() {
		
		/*
		 * Somente fara busca se this.clientes estiver vazio
		 * Isso melhora performace e diminue buscas desnecessarias
		 */
		if(this.clientes == null){
			EntityManager manager = this.getEntityManager();
			ClienteServicos cliente = new ClienteServicos(manager);
			
			List<Cliente> listaClientes = cliente.buscaTodosClientes();
			this.clientes = listaClientes;
		}

		return this.clientes;
	}
	
	private EntityManager getEntityManager(){
		FacesContext fc = FacesContext.getCurrentInstance();
		ExternalContext ex = fc.getExternalContext();
		HttpServletRequest request = (HttpServletRequest) ex.getRequest();
		EntityManager manager = (EntityManager) request.getAttribute("EntityManager");
		
		return manager;
	}
	
	public Cliente getCliente() {
		return cliente;
	}

	public void setCliente(Cliente cliente) {
		this.cliente = cliente;
	}

	public List<Cliente> getClientes() {
		return clientes;
	}

	public void setClientes(List<Cliente> clientes) {
		this.clientes = clientes;
	}
}
